package com.ruoyi.project.system.device.controller;

import java.io.*;
import java.util.*;

import cn.afterturn.easypoi.entity.ImageEntity;
import com.itextpdf.text.Paragraph;
import com.ruoyi.project.system.device.pdf.ImageTable;
import com.ruoyi.project.system.device.pdf.ReportFormUtil;
import com.ruoyi.project.system.device.domain.MyDeviceDTO;
import com.ruoyi.project.system.device.domain.MyDeviceDtailsDTO;
import com.ruoyi.project.system.device.domain.MyPlan;
import com.ruoyi.project.system.device.service.IMyDeviceDetailsService;
import com.ruoyi.project.system.device.service.IMyPlanService;
import com.ruoyi.project.utils.FileUtil;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.compress.utils.Lists;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.system.device.domain.MyDevice;
import com.ruoyi.project.system.device.service.IMyDeviceService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.ruoyi.project.system.device.pdf.ReportFormUtil.doExecPhantomJS_deleteFileAfterException;
import static com.ruoyi.project.system.device.pdf.ReportFormUtil.getPdfTable;

/**
 * 【请填写功能名称】Controller
 *
 * @author ruoyi
 * @date 2024-06-30
 */
@Controller
@RequestMapping("/system/device")
public class MyDeviceController extends BaseController
{
    private String prefix = "system/device";

    @Autowired
    private IMyDeviceService myDeviceService;
    @Autowired
    private IMyDeviceDetailsService myDeviceDetailsService;
    @Autowired
    private IMyPlanService myPlanService;
    @RequiresPermissions("system:device:view")
    @GetMapping()
    public String device(@RequestParam(value = "planId",required = false)Long planId, ModelMap mmap)
    {
        MyDeviceDTO myDeviceDTO =   myDeviceService.queryDetail(planId);
        if(planId!=null)
        {
            MyPlan myPlan = myPlanService.selectMyPlanById(planId);
            myDeviceDTO.setPlanName(myPlan.getName());
            myDeviceDTO.setSampleName(myPlan.getSampleName());
        }
        mmap.put("myDevice",myDeviceDTO);

        return prefix + "/device";
    }

    @GetMapping("/reload")
    public String  reload(@RequestParam(value = "planId",required = false)Long planId, ModelMap mmap)
    {
        MyDeviceDTO deviceDTO =  myDeviceService.queryDetail(planId);
        if(planId!=null)
        {
            MyPlan myPlan = myPlanService.selectMyPlanById(planId);
            deviceDTO.setPlanName(myPlan.getName());
            deviceDTO.setSampleName(myPlan.getSampleName());
        }
        mmap.put("myDevice",deviceDTO);

        RedirectView redirectView = new RedirectView();
        redirectView.setUrl("/device");
        //return redirectView;//redirect("/swagger-ui/index.html");//"redirect:/device";
        return prefix + "/device";
    }

    /**
     * 查询【请填写功能名称】列表
     */
    @RequiresPermissions("system:device:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(MyDevice myDevice)
    {
        startPage();
        List<MyDevice> list = myDeviceService.selectMyDeviceList(myDevice);
        return getDataTable(list);
    }

    /**
     * 导出【请填写功能名称】列表
     */
    @RequiresPermissions("system:device:export")
    @Log(title = "【设备列表导出】", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(MyDevice myDevice)
    {
        List<MyDevice> list = myDeviceService.selectMyDeviceList(myDevice);
        ExcelUtil<MyDevice> util = new ExcelUtil<MyDevice>(MyDevice.class);
        return util.exportExcel(list, "【设备列表】数据");
    }

    /**
     * 新增【请填写功能名称】
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存【请填写功能名称】
     */
    @RequiresPermissions("system:device:add")
    @Log(title = "【设备新增】", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(MyDevice myDevice)
    {
        return toAjax(myDeviceService.insertMyDevice(myDevice));
    }

    /**
     * 修改【请填写功能名称】
     */
    @RequiresPermissions("system:device:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        MyDevice myDevice = myDeviceService.selectMyDeviceById(id);
        mmap.put("myDevice", myDevice);
        return prefix + "/edit";
    }

    /**
     * 修改保存【请填写功能名称】
     */
    @RequiresPermissions("system:device:edit")
    @Log(title = "【设备列表编辑】", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(MyDevice myDevice)
    {
        return toAjax(myDeviceService.updateMyDevice(myDevice));
    }

    /**
     * 删除【请填写功能名称】
     */
    @RequiresPermissions("system:device:remove")
    @Log(title = "【设备列表删除】", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(myDeviceService.deleteMyDeviceByIds(ids));
    }

    @Log(title = "【设备明细】",businessType = BusinessType.DETAIL)
    @GetMapping("/detail")
    @ResponseBody
    public MyDeviceDTO detail(@RequestParam(value = "planId",required = false)Long planId, ModelMap mmap){
        MyDeviceDTO deviceDTO= myDeviceService.queryDetail(planId);
        if(planId!=null)
        {
            MyPlan myPlan = myPlanService.selectMyPlanById(planId);
            deviceDTO.setPlanName(myPlan.getName());
            deviceDTO.setSampleName(myPlan.getSampleName());
        }
        return deviceDTO;
    }

    @Log(title = "【设备明细】",businessType = BusinessType.DETAIL)
    @GetMapping("/saveDetail")
    @ResponseBody
    public RedirectView saveDetail(MyDeviceDTO deviceDTO, ModelMap mmap){
        MyDeviceDtailsDTO deviceDtailsDTO = deviceDTO.getDtailsDTO();
        deviceDtailsDTO.setDeviceId(deviceDTO.getId());
        myDeviceService.saveDetail(deviceDtailsDTO,deviceDTO.getSettingDTOS(),deviceDTO.getPlanId());
        mmap.put("myDevice",myDeviceService.queryDetail(deviceDTO.getDtailsDTO().getId()));
        RedirectView redirectView = new RedirectView();
        redirectView.setUrl(prefix+"/device");
        return redirectView;//redirect("/swagger-ui/index.html");//"redirect:/device";
    }

    @PostMapping("/submit")
    public String submitForm(MyDeviceDTO deviceDTO, RedirectAttributes redirectAttributes,ModelMap mmap) {
        Long planId = deviceDTO.getPlanId();

        // 判断是否需要保存
        if(deviceDTO.getChangeSel() == null || deviceDTO.getChangeSel() != 1){
            // 处理表单逻辑...
            MyDeviceDtailsDTO deviceDtailsDTO = deviceDTO.getDtailsDTO();
            deviceDtailsDTO.setDeviceId(deviceDTO.getId());
            deviceDTO.getDtailsDTO().setPlanName(deviceDTO.getPlanName());
            deviceDTO.getDtailsDTO().setSampleName(deviceDTO.getSampleName());
            planId = myDeviceService.saveDetail(deviceDTO.getDtailsDTO(),deviceDTO.getSettingDTOS(),planId);
        }

        MyDeviceDTO myDeviceDTO =   myDeviceService.queryDetail(planId);
        if(planId!=null)
        {
            MyPlan myPlan = myPlanService.selectMyPlanById(planId);
            deviceDTO.setPlanName(myPlan.getName());
            deviceDTO.setSampleName(myPlan.getSampleName());
        }
        mmap.put("myDevice",myDeviceDTO);

        // 重定向到当前页面，并带上参数
        return prefix + "/device";
        //return "redirect:device";
    }

    @GetMapping("/queryMyPlans")
    public List<MyPlan> queryMyPlans(){
        return myDeviceService.queryMyPlans();
    }


    @ApiOperation("word模板下载")
    @GetMapping("/downLoad")
    public void exportWordByModel(HttpServletResponse response, String path){
        Map<String,Object> map = new HashMap<>();
        map.put("nowTime","2023");
        map.put("p2Seting","2024");
        map.put("bujijingT2Now","tom");
        map.put("bujijingC4Seting","23");
        map.put("bujijingT3Now","男");

//        List<String> list = new ArrayList<>();
//        list.add("2019就读A学校");
//        list.add("2022就读B学校");
//        list.add("2023上岸研究生");
//        map.put("list",list);

        ImageEntity imageEntity = new ImageEntity();

        imageEntity.setUrl("D:\\exportPdf\\bars.png");
        imageEntity.setWidth(80);
        imageEntity.setHeight(100);
        map.put("photo",imageEntity);

        FileUtil.exportWordByModel(response,map,"templates/word.docx","员工统计");
    }
//    @GetMapping("/downLoad")
//    public void download(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        generatePdf();
//        String fileName = "分析报告.pdf";
//        // 输出文件
//        response.setCharacterEncoding("utf-8");
//        response.setContentType("multipart/form-data");
//        // 中文文件名支持
//        String encodedfileName = null;
//        String agent = request.getHeader("USER-AGENT");
//        if (null != agent && -1 != agent.indexOf("MSIE")) {// IE
//            encodedfileName = java.net.URLEncoder.encode(fileName, "UTF-8");
//        } else if (null != agent && -1 != agent.indexOf("Mozilla")) {
//            encodedfileName = new String(fileName.getBytes("GB2312"), "iso-8859-1");
//        } else {
//            encodedfileName = java.net.URLEncoder.encode(fileName, "UTF-8");
//        }
//        response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedfileName + "\"");
//        InputStream inputStream = null;
//        OutputStream os = null;
//        try {
//            inputStream = new FileInputStream(new File("D:\\exportPdf\\document.pdf"));
//            os = response.getOutputStream();
//            byte[] b = new byte[2048];
//            int length;
//            while ((length = inputStream.read(b)) > 0) {
//                os.write(b, 0, length);
//            }
//        } catch (Exception e) {
//            throw e;
//        } finally {
//            if (os != null) {
//                os.close();
//            }
//            if (inputStream != null) {
//                inputStream.close();
//            }
//        }
//    }

    private void generatePdf(){
        try
        {
            // 测试同时生成两张图
            // 注意：要先手动创建两个空文件G:\\test\\1.png和G:\\test\\2.png；要提前将echarts的option数据写到G:\\test\\testOption.txt和G:\\test\\testOption2.txt中
            doExecPhantomJS_deleteFileAfterException("D:\\exportPdf\\testOption.txt,D:\\exportPdf\\testOption1.txt", "D:\\exportPdf\\1.png,D:\\exportPdf\\2.png", "D:\\exportPdf\\111.png,D:\\exportPdf\\222.png");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }


        Paragraph ph1 = ReportFormUtil.createImageParagraphByPath("1、段落标题111", "D:\\exportPdf\\111.png", 35, 35,"这是一段前缀描述信息111", "这是一段后缀描述信息111");
        Paragraph ph2 = ReportFormUtil.createImageParagraphByPath("2、段落标题222", "D:\\exportPdf\\222.png", 35, 35, "这是一段前缀描述信息222", "这是一段后缀描述信息222");
        ImageTable imageTable = new ImageTable();
        imageTable.setParagraph(ph1);
        imageTable.setPdfPTable(getPdfTable());
        ImageTable imageTable1 = new ImageTable();
        imageTable1.setParagraph(ph2);
        imageTable1.setPdfPTable(getPdfTable());
        List<ImageTable> imageTables = Lists.newArrayList();
        imageTables.add(imageTable);
        imageTables.add(imageTable1);

        List<Paragraph> phs = new ArrayList<Paragraph>();
        phs.add(ph1);
        phs.add(ph2);
        //createTable();
        ReportFormUtil.createPDFDocumentToDisk("GC ADL SHANGHAI Elastomer Process", "OUTGASSING REPORT OF REQUEST TEC XXX", "", imageTables, "D:\\exportPdf\\document.pdf");
    }

    public static String writeFile(String options) {
        String dataPath="D:\\exportPdf\\"+ UUID.randomUUID().toString().substring(0, 8) +".json";
        try {
            /* 写入Txt文件 */
            File writename = new File(dataPath); // 相对路径，如果没有则要建立一个新的output.txt文件
            if (!writename.exists()) {   //文件不存在则创建文件，先创建目录
                File dir = new File(writename.getParent());
                dir.mkdirs();
                writename.createNewFile(); // 创建新文件
            }
            BufferedWriter out = new BufferedWriter(new FileWriter(writename));
            out.write(options); // \r\n即为换行
            out.flush(); // 把缓存区内容压入文件
            out.close(); // 最后记得关闭文件
        } catch (IOException e) {
            e.printStackTrace();
        }
        return dataPath;
    }

}
